package com.du.ichat;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.support.design.widget.TabLayout;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.du.ichat.databinding.ActivityMainBinding;
import com.du.ichat.fragment.ContactFragment;
import com.du.ichat.fragment.FindFragment;
import com.du.ichat.fragment.ProfileFragment;
import com.du.ichat.fragment.WeixinFragment;
import com.du.ichat.utils.BaseActivity;
import com.du.ichat.utils.SpUtils;
import com.google.zxing.Utils.Constant;
import com.google.zxing.activity.CaptureActivity;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.friend.FriendService;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.QueryDirectionEnum;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.netease.nimlib.sdk.nos.NosService;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;
import com.netease.nimlib.sdk.uinfo.model.UserInfo;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity {
    private static MainActivity instance;
    private ActivityMainBinding binding;
    private ViewPagerAdapter adapter;
    private static LoginInfo loginInfo;
    private static NimUserInfo userinfo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this , R.layout.activity_main);
        setSupportActionBar(binding.toolbar);
        instance = this;
        initTabLayout();
        initViewPager();
        loginInfo = SpUtils.getObject(this , "logininfo");
        userinfo = SpUtils.getObject(this , "userinfo");
        getFriends();
        log("avatarUrl : " + com.du.ichat.utils.UserManager.getUserinfo(this).getAvatar());



    }





    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    private void initViewPager() {
        adapter = new ViewPagerAdapter(getSupportFragmentManager());
        binding.viewpager.setAdapter(adapter);
        binding.viewpager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(binding.tabLayout));
        binding.tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(binding.viewpager));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.menu_saoyisao:
                startQR();
                break;
            case R.id.action_search:
                break;
            case R.id.menu_add_friend:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void startQR() {
        Intent intent = new Intent(this , CaptureActivity.class);
        startActivityForResult(intent , Constant.REQ_QR_CODE);
    }

        @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            //将扫描出的信息显示出来
            log( "QR info : " + scanResult);
            try {
                JSONObject qrInfo = new JSONObject(scanResult);
                String account = qrInfo.getString("account");
                Intent intent = new Intent(this , UserInfoActivity.class);
                intent.putExtra("account" , account);
                startActivity(intent);
            } catch (JSONException e) {
              Intent intent = new Intent(this , OtherQRActivity.class);
            intent.putExtra("scanResult" , scanResult);
            startActivity(intent);
            }


//            String account = scanResult.split(":")[0];
//            Intent intent = new Intent(this , UserInfoActivity.class);
//            intent.putExtra("account" , account);
//            startActivity(intent);
        }
    }

    private void initTabLayout(){
        addTab(R.drawable.tab_weixin_selector , "微信");
        addTab(R.drawable.tab_contact_selector , "通讯录");
        addTab(R.drawable.tab_find_selector , "发现");
        addTab(R.drawable.tab_profile_selector , "我");
    }

    private void addTab(int resId , String string ){
        View view = getLayoutInflater().inflate(R.layout.tab_item , null , false);
        TabLayout.Tab tab = binding.tabLayout.newTab();
        TextView tv = view.findViewById(R.id.tab_item_tv);
        tv.setText(string);
        ImageView iv = view.findViewById(R.id.tab_item_iv);
        iv.setImageResource(resId);
        tab.setCustomView(view);
        binding.tabLayout.addTab(tab);
    }

    public class ViewPagerAdapter extends FragmentPagerAdapter {


        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            Fragment fragment = FragmentProvider.getInstance(position);
            return fragment;
        }

        @Override
        public int getCount() {
            return 4;
        }
    }

    public static class FragmentProvider{
        public final static int FRAGMENT_WEIXIN_ID = 0;
        public final static int FRAGMENT_CONTACT_ID = 1;
        public final static int FRAGMENT_FIND_ID = 2;
        public final static int FRAGMENT_PROFILE_ID = 3;
        public static Fragment getInstance(int index){
            Fragment fragment = null;
            switch (index){
                case FRAGMENT_WEIXIN_ID:
                    fragment = new WeixinFragment();
                    break;
                case FRAGMENT_CONTACT_ID:
                    fragment = new ContactFragment();
                    break;
                case FRAGMENT_FIND_ID:
                    fragment = new FindFragment();
                    break;
                case FRAGMENT_PROFILE_ID:
                    fragment = new ProfileFragment();
                    break;
            }

            return fragment;
        }
    }

    public static void finishThis(){
        instance.finish();
    }


    private void getFriends(){
        List<String> friends = NIMClient.getService(FriendService.class).getFriendAccounts();
        NIMClient.getService(UserService.class).fetchUserInfo(friends)
                .setCallback(new RequestCallback<List<NimUserInfo>>() {
                    @Override
                    public void onSuccess(List<NimUserInfo> nimUserInfos) {
                        ArrayList<NimUserInfo> list = new ArrayList<>();
                        list.addAll(nimUserInfos);
                        SpUtils.putObject(MainActivity.this , "friends" , list);
                    }

                    @Override
                    public void onFailed(int i) {

                    }

                    @Override
                    public void onException(Throwable throwable) {

                    }
                });
    }




}
